package middleware

import (
	"fmt"
	"hft/Database/admin"
	utils "hft/Http/Utils"
	"hft/e"
	"hft/global"
	"hft/tools"

	"github.com/gin-gonic/gin"
)

func ApiPower() gin.HandlerFunc {
	return func(c *gin.Context) {
		if claims, err := tools.GetClaims(c); err != nil {
			utils.FailWithMessage(e.InValidToken, c)
			c.Abort()
			return
		} else {
			var apis []*admin.Api
			global.OC_DB.Raw(fmt.Sprintf("SELECT * FROM hft_roles_apis LEFT JOIN hft_apis ON hft_roles_apis.api_id = hft_apis.id WHERE role_id = %v", claims.RoleID)).Scan(&apis)
			if ok := IsCanThisPath(c.Request.URL.Path, apis); !ok {
				utils.FailWithMessage(fmt.Sprintf("%v未开通,请联系客服开通", c.Request.URL.Path), c)
				c.Abort()
				return
			}
			c.Next()
		}
		// c.Next()
	}
}

// 判断是否存在该路径
func IsCanThisPath(path string, list []*admin.Api) bool {
	for _, v := range list {
		// fmt.Println(v.ID, v.ApiPath, v.ApiName, v.ApiType, path, method)
		if v.ApiPath == path {
			return true
		}
	}
	return false
}
